// pages/cart/cart.js
Page({
    data: {
        cartItems: [],
        totalPrice: 0,
        allSelected: false,
        startX: 0,
        slideOffset: 0
    },

    onShow() {
        this.loadCartItems();
    },

    loadCartItems() {
        const cartItems = wx.getStorageSync('cartItems') || [];
        const updatedCartItems = cartItems.map(item => ({
            ...item,
            selected: false,
            slideOffset: 0
        }));
        
        this.setData({
            cartItems: updatedCartItems,
            totalPrice: 0,
            allSelected: false
        });
    },

    toggleSelectAll() {
        const { cartItems, allSelected } = this.data;
        const newAllSelected = !allSelected;
        
        const updatedCartItems = cartItems.map(item => ({
            ...item,
            selected: newAllSelected
        }));

        this.setData({
            allSelected: newAllSelected,
            cartItems: updatedCartItems
        });

        this.updateTotalPrice();
    },

    toggleItemSelect(e) {
        const { index } = e.currentTarget.dataset;
        const { cartItems } = this.data;
        
        cartItems[index].selected = !cartItems[index].selected;
        
        const allSelected = cartItems.every(item => item.selected);

        this.setData({
            cartItems,
            allSelected
        });

        this.updateTotalPrice();
    },

    updateTotalPrice() {
        const totalPrice = this.data.cartItems
            .filter(item => item.selected)
            .reduce((total, item) => {
                return total + (item.price * item.quantity);
            }, 0)
            .toFixed(2);

        this.setData({ totalPrice });
    },

    increaseQuantity(e) {
        const { index } = e.currentTarget.dataset;
        const cartItems = [...this.data.cartItems];
        cartItems[index].quantity += 1;
        this.updateCart(cartItems);
    },

    decreaseQuantity(e) {
        const { index } = e.currentTarget.dataset;
        const cartItems = [...this.data.cartItems];
        if (cartItems[index].quantity <= 1) {
            wx.showModal({
                title: '提示',
                content: '是否删除该商品？',
                success: (res) => {
                    if (res.confirm) {
                        cartItems.splice(index, 1);
                    }
                    this.updateCart(cartItems);
                }
            });
            return;
        }
        cartItems[index].quantity -= 1;
        this.updateCart(cartItems);
    },

    updateQuantity(e) {
        const { index } = e.currentTarget.dataset;
        let { value } = e.detail;
        const cartItems = [...this.data.cartItems];

        value = parseInt(value) || 0;
        if (value <= 0) {
            wx.showModal({
                title: '提示',
                content: '是否删除该商品？',
                success: (res) => {
                    if (res.confirm) {
                        cartItems.splice(index, 1);
                    } else {
                        cartItems[index].quantity = 1;
                    }
                    this.updateCart(cartItems);
                }
            });
            return;
        }

        cartItems[index].quantity = value;
        this.updateCart(cartItems);
    },

    touchStart(e) {
        const touch = e.touches[0];
        this.setData({
            startX: touch.clientX
        });
    },

    touchMove(e) {
        const touch = e.touches[0];
        const { index } = e.currentTarget.dataset;
        const { cartItems, startX } = this.data;
        
        let offset = touch.clientX - startX;
        // 限制只能左滑
        if (offset > 0) offset = 0;
        // 限制最大滑动距离
        if (offset < -140) offset = -140;

        const updatedCartItems = [...cartItems];
        updatedCartItems[index].slideOffset = offset;

        this.setData({
            cartItems: updatedCartItems
        });
    },

    touchEnd(e) {
        const { index } = e.currentTarget.dataset;
        const { cartItems } = this.data;
        const offset = cartItems[index].slideOffset;

        const updatedCartItems = [...cartItems];
        // 如果滑动距离超过70rpx，则完全展开删除按钮
        updatedCartItems[index].slideOffset = offset < -70 ? -140 : 0;

        this.setData({
            cartItems: updatedCartItems
        });
    },

    deleteItem(e) {
        const { index } = e.currentTarget.dataset;
        const cartItems = [...this.data.cartItems];
        cartItems.splice(index, 1);
        this.updateCart(cartItems);
    },

    updateCart(cartItems) {
        const totalPrice = this.calculateTotal(cartItems);
        const allSelected = cartItems.length > 0 && cartItems.every(item => item.selected);
        
        this.setData({
            cartItems,
            totalPrice,
            allSelected
        });
        
        wx.setStorageSync('cartItems', cartItems);

        const pages = getCurrentPages();
        const menuPage = pages.find(page => page.route === 'pages/menu/menu');
        if (menuPage) {
            const selectedDishes = {};
            cartItems.forEach(item => {
                selectedDishes[item.id] = item.quantity;
            });
            menuPage.setData({ selectedDishes });
        }
    },

    calculateTotal(items) {
        return items
            .filter(item => item.selected)
            .reduce((total, item) => {
                return total + (item.price * item.quantity);
            }, 0).toFixed(2);
    },

    goToCheckout() {
        const selectedItems = this.data.cartItems.filter(item => item.selected);
        if (selectedItems.length === 0) {
            wx.showToast({
                title: '请选择要结算的商品',
                icon: 'none'
            });
            return;
        }
        // TODO: 实现结算功能
        wx.showToast({
            title: '正在开发中...',
            icon: 'none'
        });
    }
});
